package com;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class ServerThread extends PublicThread {
	private ClientThread client = null;

	ServerThread(Socket socket, ThreadPool pool) {
		this.socket = socket;
		this.threadPool = pool;
		addToThreadPool();
	}

	public void run() {
		InputStream in = null;
		byte[] data = new byte[4096];
		int lenght = 0;

		try {
			in = socket.getInputStream();
			while (isRun && lenght > -1) {
				if (client.isConnect()) {
					lenght = in.read(data);
					if (lenght > 0) {
						String o = new String(data);
						client.send(data, 0, lenght);
						System.out.println("Data:  " + o.substring(0, o.length() > 20 ? 20 : o.length()));
					}
				}
				sleep(10);
			}
			client.close();
		} catch (IOException e) {
			System.out.println("ServerThread Error " + e.getMessage());
		}

		close();
		removeFromThreadPool();
	}

	public void close() {
		synchronized (this) {
			try {
				super.closeThread();
			} catch (Exception e1) {
				System.out.print("close ServerThread socket Error, Port:" + serverSocket.getLocalPort());
			}
		}
	}

	public void setClient(ClientThread client2) {
		this.client = client2;
	}

	public void send(byte[] data, int s, int l) {
		synchronized (this) {
			if (socket != null) {
				try {
					socket.getOutputStream().write(data, s, l);
				} catch (IOException e) {
					System.out.println(e.getMessage() + "ServerThread Send Data Error, Address: "
							+ socket.getInetAddress().getHostAddress() + ", Port: " + socket.getPort());
				}
			}
		}
	}

}
